#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # 重置颜色

# 检查是否以root运行
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}错误：请使用sudo运行此脚本${NC}"
    exit 1
fi

# 配置参数（可修改）
RELAY_SERVER="your-relay-server.com"  # 替换为你的中继服务器
CONFIG_URL="https://vip.123pan.cn/1825477870/1/RustDesk2.toml"  # 配置模板

# 函数：显示进度消息
progress() {
    echo -e "${YELLOW}[进度] $1${NC}"
}

# 函数：显示成功消息
success() {
    echo -e "${GREEN}[成功] $1${NC}"
}

# 函数：显示错误消息
error() {
    echo -e "${RED}[错误] $1${NC}"
    exit 1
}

# ========== 主安装流程 ==========

# 1. 配置Flatpak国内镜像
progress "正在配置Flatpak国内镜像源..."
flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo || error "添加Flathub源失败"
flatpak remote-modify flathub --url=https://mirrors.ustc.edu.cn/flathub || error "修改镜像源失败"
success "Flatpak国内镜像配置完成"

# 2. 安装RustDesk
progress "正在安装RustDesk..."
flatpak install -y flathub com.rustdesk.RustDesk || error "安装RustDesk失败"
success "RustDesk安装完成"

# 3. 下载配置文件
progress "正在配置中继服务器..."
RUSTDESK_CONFIG_DIR="/home/$(logname)/.var/app/com.rustdesk.RustDesk/config/rustdesk"
mkdir -p "$RUSTDESK_CONFIG_DIR"

if wget -q "$CONFIG_URL" -O "$RUSTDESK_CONFIG_DIR/RustDesk2.toml"; then
    # 替换默认服务器地址
    sed -i "s|rendezvous_server = .*|rendezvous_server = '$RELAY_SERVER'|" "$RUSTDESK_CONFIG_DIR/RustDesk2.toml"
    chown -R $(logname): "$RUSTDESK_CONFIG_DIR"
    success "中继服务器配置完成"
else
    error "配置文件下载失败"
fi

# 4. 创建快捷方式
progress "正在创建快捷方式..."
cat > /home/liveuser/Desktop/rustdesk.desktop <<EOL
[Desktop Entry]
Name=RustDesk
Exec=flatpak run com.rustdesk.RustDesk
Icon=/var/lib/flatpak/app/com.rustdesk.RustDesk/current/active/files/share/icons/hicolor/256x256/apps/com.rustdesk.RustDesk.png
Terminal=false
Type=Application
Categories=Network;RemoteAccess;
EOL
success "快捷方式已创建"

# 5. 设置适当权限（更安全的替代方案）
progress "正在设置应用程序权限..."
sudo chmod -R 777 /var/home/liveuser/.var/app/com.rustdesk.RustDesk/

success "权限设置完成"

# 6. 完成提示
echo -e "${GREEN}
========================================
  RustDesk 已成功安装并配置！
  中继服务器: $RELAY_SERVER
  启动方式:
  1. 闲鱼：Steamos超人制作
  2. 在桌面上点击 RustDesk 图标
========================================${NC}"
